const { reqWithSSL, delWithSSL } = require('./util')
const runtimeLogger = require('../log4js')()

async function getServiceWithCondition(ip, condition, port = 30100) {
  const ans = []
  const { services } = await getAllServices(ip, port)
  for (const service of services) {
    const { serviceId, appId, serviceName, version, level, schemas, status, environment } = service
    const { cAppId, cServiceName, cVersion, cEnv, cSchema } = condition
    if (
      checkEqualsUdefable(cAppId, appId) &&
      checkEqualsUdefable(cServiceName, serviceName) &&
      checkEqualsUdefable(cVersion, version) &&
      checkEqualsUdefable(cEnv, environment)
    ) {
      if (!cSchema || (schemas && schemas.includes(cSchema))) {
        ans.push(service)
      }
    }
  }
  return Promise.resolve({ services: ans })
}

async function delServiceWithCondition(ip, condition, force, port = 30100) {
  runtimeLogger.log(`[delServiceWithCondition]: Invoke del service with condition: ${JSON.stringify(condition)} on ip: ${ip}:${port}`)
  const { services } = await getAllServices(ip, port)
  for (const service of services) {
    const { appId, serviceName, version, environment, serviceId } = service
    const { cAppId, cServiceName, cVersion, cEnv } = condition
    if (
      cAppId === appId &&
      cServiceName === serviceName &&
      checkEqualsUdefable(cVersion, version) &&
      checkEqualsUdefable(cEnv, environment)
    ) {
      runtimeLogger.log(`[delServiceWithCondition]: find match service appId: ${appId}; serviceName: ${serviceName}; version: ${version}; env: ${environment}. Do delete!`)
      return delServiceByServiceId(serviceId, ip, force, port)
    }
  }
}

function getAllServices(ip, port = 30100) {
  const url = `https://${ip}:${port}/v4/default/registry/microservices`
  return reqWithSSL(url).then(({ data }) => {
    console.log('=======================')
    console.log(JSON.stringify(data))
    console.log('=======================')
    return data
  }).catch(err => {
    // handle err
    throw new Error(`获取所有的MicroServices失败: ${err}; Error.response: ${err && err.response && JSON.stringify(err.response.data)}. Search string: ${this.searchStr}`)
  })
}

function delServiceByServiceId(serviceId, ip, force, port = 30100) {
  const url = `https://${ip}:${port}/v4/default/registry/microservices/${serviceId}?force=${!!force}`
  return delWithSSL(url).then(data => {
    console.log('=======================')
    console.log(JSON.stringify(data))
    console.log('=======================')
    return data || 'OK'
  }).catch(err => {
    // handle err
    throw new Error(`删除指定的MicroServices失败: ${err}; Error.response: ${err && err.response && JSON.stringify(err.response.data)}. Search string: ${this.searchStr}`)
  })
}

/**
 * 比较a和b是否相等, a为undefined时直接返回相等
 * @param a 字符串
 * @param b 字符串
 */
function checkEqualsUdefable(a, b) {
  if (a === undefined) {
    return true
  }
  return a === b
}

module.exports = { getAllServices, getServiceWithCondition, delServiceWithCondition }
